//
//  ZYWeChatHandler.m
//  SuiTong
//
//  Created by 石志愿 on 2020/9/3.
//  Copyright © 2020 石志愿. All rights reserved.
//

#import "ZYWeChatHandler.h"
#import "ZYShareManager.h"
#import "WXApi.h"

@interface ZYWeChatHandler ()<WXApiDelegate>

/// 登录回调
@property (nonatomic, copy) ZYThirdLoginBlock loginCompletion;
/// 分享回调
@property (nonatomic, copy) ZYThirdShareBlock shareCompletion;

@end

@implementation ZYWeChatHandler

- (void)registerApp {
    [WXApi registerApp:kWxAppKey universalLink:kWXUniversalLink];
}

- (BOOL)installWeChat {
    return [WXApi isWXAppInstalled];
}

// 处理应用拉起协议
- (BOOL)HandleOpenURL:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:self];
}

// 处理应用的UniversalLink拉起协议
- (BOOL)HandleUniversalLink:(NSUserActivity *)userActivity {
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

//MARK: 分享

//分享网页
- (void)shareWebPage:(ZYThirdShareInfo *)info platform:(ZYSharePlatform)platform completion:(__nullable ZYThirdShareBlock)completion {
    if ([NSString isEmpty:info.url]) {
        [MBProgressHUD showMessage:@"分享链接不能为空"];
        return;
    }
    NSURL *url = [NSURL URLWithString:info.url];
    if (!url) {
        [MBProgressHUD showMessage:@"分享链接错误"];
        return;
    }
    
    if ([NSString isEmpty:info.title]) {
        info.title = @"ZYThirdShare";
    }
    
    if ([NSString isEmpty:info.desc]) {
        info.desc = @"ZYThirdShare分享";
    }
    
    NSData *imageData = nil;
    if (info.icon) {
        imageData = [info.icon compressWithMaxWidth:100 maxSizeKB:10];
    } else {
        UIImage *image = [UIImage imageNamed:@"share_logo"];
        if (image) {
            imageData = UIImageJPEGRepresentation(image, 1.0);
        }
    }
    
    WXWebpageObject *obj = [[WXWebpageObject alloc]init];
    obj.webpageUrl = info.url;
    
    WXMediaMessage *message = [[WXMediaMessage alloc]init];
    message.title = info.title;
    message.description = info.desc;
    message.mediaObject = obj;
    message.thumbData = imageData;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    req.bText = false;
    req.message = message;
    [self sendShare:req platform:platform completion:completion];
}

//分享图片
- (void)shareImage:(UIImage *)image thumbImage:(UIImage *)thumbImage  platform:(ZYSharePlatform)platform completion:(__nullable ZYThirdShareBlock)completion {
    if (!image) {
        return;
    }
    
    WXImageObject *obj = [[WXImageObject alloc]init];
    obj.imageData = UIImagePNGRepresentation(image);
    
    WXMediaMessage *message = [[WXMediaMessage alloc]init];
    if (thumbImage) {
        [message setThumbImage:thumbImage];
    }
    message.mediaObject = obj;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    req.bText = false;
    req.message = message;
    [self sendShare:req platform:platform completion:completion];
}

//分享文本
- (void)shareText:(NSString *)text platform:(ZYSharePlatform)platform completion:(__nullable ZYThirdShareBlock)completion {
            
      SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
      req.bText = false;
      req.text = text;
      [self sendShare:req platform:platform completion:completion];
}

- (void)sendShare:(SendMessageToWXReq *)req platform: (ZYSharePlatform)platform completion:(__nullable ZYThirdShareBlock)completion {
    self.shareCompletion = completion;

    if (platform == ZYSharePlatformWXSession) {
        req.scene = WXSceneSession;
    } else if (platform == ZYSharePlatformWXTimeline) {
        req.scene = WXSceneTimeline;
    }
    [WXApi sendReq:req completion:nil];
}

//MARK: 登录

- (void)login:(__nullable ZYThirdLoginBlock)completion {
    self.loginCompletion = completion;
    if ([self installWeChat]) {
        SendAuthReq *req = [[SendAuthReq alloc]init];
        //应用授权作用域，如获取用户个人信息则填写snsapi_userinfo
        req.scope = @"snsapi_userinfo";
        req.state = @"App";
        [WXApi sendReq:req completion:nil];
    }
}

/// 微信授权并获取用户信息
- (void)requestWXAuth:(SendAuthResp *)resp {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"appid"] = kWxAppKey;
    params[@"secret"] = kWxSecret;
    params[@"code"] = resp.code;
    params[@"grant_type"] = @"authorization_code";
    [[ZYShareManager shared] get:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:params showLoading:YES success:^(id  _Nonnull response) {
        NSString *token = response[@"access_token"];
        NSString *openId = response[@"openid"];
        if (![NSString isEmpty:token] && ![NSString isEmpty:openId]) {
            [self requestWXUserInfo:token openId:openId];
        } else {
            if (self.loginCompletion) {
                self.loginCompletion(nil, ZYShareStatusFailed);
            }
        }
    } failure:^(NSError * _Nonnull error) {
        if (self.loginCompletion) {
            self.loginCompletion(nil, ZYShareStatusFailed);
        }
    }];
}

- (void)requestWXUserInfo:(NSString *)token openId:(NSString *)openId {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"access_token"] = token;
    params[@"openid"] = openId;
    [[ZYShareManager shared] get:@"https://api.weixin.qq.com/sns/userinfo" parameters:params showLoading:YES success:^(id  _Nonnull response) {
        ZYThirdLoginInfo *info = [ZYThirdLoginInfo mj_objectWithKeyValues:response];
        info.platform = ZYThirdLoginPlatformWeChat;
        info.imageUrl = response[@"headimgurl"];
        info.gender = response[@"sex"];
        if (self.loginCompletion) {
            self.loginCompletion(info, ZYShareStatusSuccess);
        }
    } failure:^(NSError * _Nonnull error) {
        if (self.loginCompletion) {
            self.loginCompletion(nil, ZYShareStatusFailed);
        }
    }];
}

/// 刷新并延长token有效期
- (void)refreshWXAccessToken:(NSString *)oldToken {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"appid"] = kWxAppKey;
    params[@"refresh_token"] = oldToken;
    params[@"grant_type"] = @"refresh_token";
    [[ZYShareManager shared] get:@"https://api.weixin.qq.com/sns/oauth2/refresh_token" parameters:params showLoading:YES success:^(id  _Nonnull response) {
    } failure:^(NSError * _Nonnull error) {
    }];
}

//MARK: WXApiDelegate

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:SendMessageToWXResp.class]) {
        //分享回调
        if (resp.errCode == 0) {
            if (self.shareCompletion) {
                self.shareCompletion(ZYShareStatusSuccess);
            }
        } else {
            if (self.shareCompletion) {
                self.shareCompletion(ZYShareStatusFailed);
            }
        }
    } else if ([resp isKindOfClass:SendAuthResp.class]) {
        // 登录回调
        if (resp.errCode == 0 && resp.type == 0) {
            //授权成功
            SendAuthResp *response = (SendAuthResp *)resp;
            ZYThirdLoginInfo *info = [[ZYThirdLoginInfo alloc]init];;
            info.platform = ZYThirdLoginPlatformWeChat;
            info.respCode = response.code;
            if (self.loginCompletion) {
                self.loginCompletion(info, ZYShareStatusSuccess);
            }
            //直接返回，由后台来请求用户信息
//            [self requestWXAuth:response];
        } else {
            if (self.loginCompletion) {
                self.loginCompletion(nil, ZYShareStatusFailed);
            }
            DEBUGLog(@"微信授权错误码:%d, %@",resp.errCode, resp.errStr);
        }
        
    } else if ([resp isKindOfClass:PayResp.class]) {
        // 支付回调
        if (resp.errCode == 0) {
            //  支付成功
        } else {
            //  支付失败
        }
    }
}

@end
